package com.example.shixun1.adapter;

import android.content.Context;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupMenu;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.shixun1.R;
import com.example.shixun1.model.User;
import java.util.List;

public class AccountAdapter extends RecyclerView.Adapter<AccountAdapter.ViewHolder> {
    private final Context context;
    private final List<User> accountList;
    private final AccountActionListener listener;
    private boolean showAllPasswords = false;
    private final SparseBooleanArray passwordVisibility = new SparseBooleanArray();

    public interface AccountActionListener {
        void onEditAccount(int position, User user);
        void onDeleteAccount(int position, User user);
        void onToggleAdminStatus(int position, User user);
    }

    public AccountAdapter(Context context, List<User> accountList, AccountActionListener listener) {
        this.context = context;
        this.accountList = accountList;
        this.listener = listener;
    }

    public void updatePassword(int position, String newPassword) {
        accountList.get(position).updatePassword(newPassword);
        notifyItemChanged(position);
    }

    public void toggleAllPasswordsVisibility() {
        showAllPasswords = !showAllPasswords;
        notifyDataSetChanged();
    }

    public void togglePasswordVisibility(int position) {
        boolean isVisible = !passwordVisibility.get(position, false);
        passwordVisibility.put(position, isVisible);
        notifyItemChanged(position);
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context)
                .inflate(R.layout.item_account, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        User user = accountList.get(position);
        boolean isVisible = showAllPasswords || passwordVisibility.get(position, false);

        holder.tvUsername.setText(String.format("账号: %s", user.getUsername()));
        holder.tvPassword.setText(String.format("密码: %s",
                isVisible ? user.getPassword() : "••••••"));
        holder.tvPassword.setCompoundDrawablesWithIntrinsicBounds(
                0, 0, isVisible ? R.drawable.ic_visibility_off : R.drawable.ic_visibility, 0);

        holder.tvAdminFlag.setVisibility(user.isAdmin() ? View.VISIBLE : View.GONE);

        holder.tvPassword.setOnClickListener(v -> togglePasswordVisibility(position));
        holder.itemView.setOnClickListener(v -> listener.onEditAccount(position, user));
        holder.itemView.setOnLongClickListener(v -> {
            showOptionsMenu(v, position, user);
            return true;
        });
    }
    private void showOptionsMenu(View anchorView, int position, User user) {
        PopupMenu popupMenu = new PopupMenu(context, anchorView);
        popupMenu.inflate(R.menu.menu_account_actions);
        // 添加删除账号的菜单项（如果不存在）
        if (popupMenu.getMenu().findItem(R.id.menu_delete) == null) {
            popupMenu.getMenu().add(0, R.id.menu_delete, 0, "删除账号");
        }

        popupMenu.setOnMenuItemClickListener(item -> {
            int itemId = item.getItemId();
            if (itemId == R.id.menu_delete) {
                // 添加确认对话框
                new android.app.AlertDialog.Builder(context)
                        .setTitle("确认删除")
                        .setMessage("确定要删除账号 " + user.getUsername() + " 吗？")
                        .setPositiveButton("确定", (dialog, which) -> {
                            listener.onDeleteAccount(position, user);
                        })
                        .setNegativeButton("取消", null)
                        .show();
                return true;
            }
            return false;
        });

        popupMenu.show();
    }

    @Override
    public int getItemCount() { return accountList.size(); }

    static class ViewHolder extends RecyclerView.ViewHolder {
        TextView tvUsername, tvPassword, tvAdminFlag;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            tvUsername = itemView.findViewById(R.id.tv_username);
            tvPassword = itemView.findViewById(R.id.tv_password);
            tvAdminFlag = itemView.findViewById(R.id.tv_admin_flag);
        }
    }
}